<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'doupload.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  <%!
   String newName(String name){
	  int pos=name.lastIndexOf('.');//后缀
	  String prefix=name.substring(pos==-1?0:pos);
	  return UUID.randomUUID()+prefix;//随机生成一个32位的文件名	 
  }
  %>
    <%
    request.setCharacterEncoding("utf-8");
    FileItemFactory factory=new  DiskFileItemFactory();
    ServletFileUpload upload=new ServletFileUpload(factory);
    List<FileItem> fields=upload.parseRequest(request);
    String picPath=application.getRealPath("news/images");//存放路径,本项目中
    for(FileItem f:fields){
    	if(f.isFormField()){ 		
    		out.print("<h1>这是表单域："+f.getFieldName()+",value"+f.getString("utf-8")+"</h1>");
    	}else
    	{
    		if(f.getName()==""){
    			continue;			
    		}
    		out.print("<h1>文件名,文件名是:"+f.getName()+"</h1>");
    		String newFileName=newName(f.getName());
    		f.write(new java.io.File(picPath,newFileName));//存入文件
    		out.print("<img src='news/images/"+newFileName+"'/>");
    	}
    	
    }
    %>
    
  </body>
</html>
